<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { type FormInstance, ElMessage } from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import { type getRegulator } from "@/api/personnel/personnel-list/types/index"
import { getRegulatorDataApi, updateRegulatorDataApi } from "@/api/personnel/personnel-list/index"
import { Search, Refresh } from "@element-plus/icons-vue"
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const dialogVisible = ref(false)
const searchData = reactive({
  team: "",
  job: ""
})
defineOptions({
  name: "personnelRegulator"
})

// 页面加载优化
const loading = ref(true)
//  #region 列表数据
const tableData = ref<getRegulator[]>([])
const tableTotal = ref<number>()
const tableDataTime = ref()
const getAddRegulator = () => {
  getRegulatorDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    team: searchData.team,
    job: searchData.job,
    state: "1"
  })
    .then((res: any) => {
      tableData.value = res.data.taskList
      tableDataTime.value = res.time
      tableTotal.value = res.data.total
      console.log(tableData.value, "页面所有数据")
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
// #endregion

// #region
//用于存放随机数用于key属性的绑定
const reload = ref()

// 多选框的列表，列出表格的每一列
const checkBoxGroup = ref(["日期", "归属团队", "职位", "人数", "学历", "工作经验", "性别", "最高年龄", "最低年龄"])

// 当前选中的多选框，代表当前展示的列
const checkedColumns = ref(["日期", "归属团队", "职位", "人数", "学历", "工作经验", "性别", "最高年龄", "最低年龄"])

// colData中列出表格中的每一列，默认都展示
const colData = reactive([
  { title: "日期", istrue: true },
  { title: "归属团队", istrue: true },
  { title: "职位", istrue: true },
  { title: "人数", istrue: true },
  { title: "学历", istrue: true },
  { title: "工作经验", istrue: true },
  { title: "性别", istrue: true },
  { title: "最高年龄", istrue: true },
  { title: "最低年龄", istrue: true }
])

// 监听checkedColumns的变化，当checkedColumns发生变化时，重新渲染表格
const watchCheckedColumns = () => {
  // 遍历colData，将colData中的istrue属性设置为false
  colData.forEach((item) => {
    item.istrue = false
  })
  // 遍历checkedColumns，将checkedColumns中的值在colData中找到对应的列，将istrue属性设置为true
  checkedColumns.value.forEach((item) => {
    colData.forEach((col) => {
      if (item === col.title) {
        col.istrue = true
      }
    })
  })
  // 重新渲染表格
  reload.value = Math.random()
}
// #endregion

// #region 打开反馈信息框并验证
const formRefFormID = ref<number>()
const formRefFormState = ref<string>()
const formRef = ref<FormInstance | null>(null)
const handleDelete = (row: getRegulator) => {
  dialogVisible.value = true
  formRefFormID.value = row.id
  formRefFormState.value = row.state
  console.log("---打开按钮", row)
}
const form = ref({
  list: [
    {
      name: "",
      sex: "",
      age: ""
    }
  ]
})
// 增加
const addItem = (a: any) => {
  form.value.list.push({
    name: "",
    age: "",
    sex: ""
  })
  console.log(a, "---------a")
}
// 删除
const deleteItem = (item: any, index: number) => {
  form.value.list.splice(index, 1)
  console.log(item)
}
const onSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 讲这个值传给接口
      console.log("---拿到id", formRefFormID.value)
      console.log("---拿到状态", formRefFormState.value)
      const s = ref<any>("")
      for (let i = 0; i < form.value.list.length; i++) {
        s.value += form.value.list[i].name + "-" + form.value.list[i].sex + "-" + form.value.list[i].age + "&"
      }
      updateRegulatorDataApi({
        id: formRefFormID.value,
        state: "3",
        message: s.value
      }).then(() => {
        console.log("修改成功")
        dialogVisible.value = false
        getAddRegulator()
        ElMessage.success("提交成功")
      })

      console.log(s.value)

      dialogVisible.value = false
    }
  })
}
// #endregion

// #region 时间转换 监听分页参数的变化
function timestampToTime(timestamp: any) {
  // 时间戳为10位需*1000，时间戳为13位不需乘1000
  const date = new Date(timestamp)
  const Y = date.getFullYear() + "-"
  const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-"
  const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " "
  return Y + M + D
}
const resetForm = () => {
  clearValidate()
}
watch([() => paginationData.currentPage, () => paginationData.pageSize], getAddRegulator, { immediate: true })
// 清空表单验证
const clearValidate = () => {
  formRef.value?.clearValidate()
  form.value.list = [
    {
      name: "",
      sex: "",
      age: ""
    }
  ]
}
// #endregion

// #region 搜索

const searchFormRef = ref<FormInstance | null>(null)
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getAddRegulator()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getAddRegulator()
  }
  paginationData.currentPage = 1
}
// #endregion
</script>

<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="team" label="归属团队">
          <el-input v-model.trim="searchData.team" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="job" label="职位">
          <el-input v-model.trim="searchData.job" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
        <!-- <el-tooltip content="下载">
              <el-button type="primary" class="XZ" :icon="Download" circle @click="downLoad" />
            </el-tooltip> -->
      </el-form>
    </el-card>
    <el-card>
      <!-- 筛查 -->
      <el-icon :size="20" style="float: right; font-size: 33px" class="show-col-btn">
        <el-popover placement="bottom" trigger="hover" width="80">
          <template #reference>
            <el-icon :size="20"><Operation /></el-icon>
          </template>
          <div>
            <el-checkbox-group v-model="checkedColumns" @change="watchCheckedColumns" class="checkbox-wrap">
              <el-checkbox
                size="large"
                style="display: block"
                v-for="item in checkBoxGroup"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-checkbox-group>
          </div>
        </el-popover>
      </el-icon>
      <div class="table-center">
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <!-- 用插槽替换时间戳转换为日期 -->
          <el-table-column v-if="colData[0].istrue" label="日期" align="center">
            <template #default="scope">
              {{ timestampToTime(scope.row.create) }}
            </template>
          </el-table-column>
          <el-table-column v-if="colData[1].istrue" prop="team" label="归属团队" align="center" />
          <el-table-column v-if="colData[2].istrue" prop="job" label="职位" align="center" />
          <el-table-column v-if="colData[3].istrue" prop="num" label="人数" align="center" />
          <el-table-column v-if="colData[4].istrue" prop="education" label="学历" align="center" />
          <el-table-column v-if="colData[5].istrue" prop="exp" label="工作经验" align="center" />
          <el-table-column v-if="colData[6].istrue" prop="sex" label="性别" align="center" />
          <el-table-column v-if="colData[7].istrue" label="年龄" align="center">
            <template #default="scope"> {{ scope.row.minAge }}-{{ scope.row.maxAge }} </template>
          </el-table-column>
          <el-table-column v-if="colData[8].istrue" label="完成情况" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleDelete(scope.row)">提交</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 反馈信息框 -->
    <el-dialog v-model="dialogVisible" title="任务信息详情" width="30%" @close="resetForm">
      <el-scrollbar height="400px">
        <el-form :model="form" ref="formRef" label-width="120px">
          <!-- <el-form-item label="统计信息" prop="desc">
          <el-input v-model="formTextaear.desc" type="textarea" />
        </el-form-item> -->
          <div v-for="(item, index) in form.list" :key="index" class="list-form">
            <el-form-item
              class="form-style"
              label="姓名"
              :prop="'list.' + index + '.name'"
              :rules="[{ required: true, message: '姓名不能为空', trigger: 'blur' }]"
            >
              <el-input v-model="item.name" placeholder="请填写姓名" style="width: 200px" />
            </el-form-item>
            <el-form-item
              class="form-style"
              label="性别"
              :prop="'list.' + index + '.sex'"
              :rules="[{ required: true, message: '性别不能为空', trigger: 'blur' }]"
            >
              <el-input v-model="item.sex" placeholder="请填写性别" style="width: 200px" />
            </el-form-item>
            <el-form-item
              class="form-style"
              label="年龄"
              :prop="'list.' + index + '.age'"
              :rules="[{ required: true, message: '年龄不能为空', trigger: 'blur' }]"
            >
              <el-input v-model="item.age" placeholder="请填写年龄" style="width: 200px" />
            </el-form-item>

            <el-form-item label-width="0" class="form-button">
              <el-button v-if="index + 1 == form.list.length" type="primary" @click="addItem(form.list.length)">
                +
              </el-button>
              <el-button v-if="index !== 0" type="danger" @click="deleteItem(item, index)"> - </el-button>
            </el-form-item>
          </div>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
